package com.mobile.check.present;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import com.mobile.check.activitys.LocalTaskListActivity;
import com.mobile.check.beans.TaskInfo;
import com.mobile.check.beans.TaskItemInfo;
import com.mobile.check.db.EntityManager;

/**
 * 类名: LocalTaskListPresent
 * 作者: 李学伟
 * 日期: 2020年10月13日 17:00
 * 描述:
 */
public class LocalTaskListPresent extends BasePresent<LocalTaskListActivity> {
    public void loadDatasFromFile(final int taskType) {
        final List<TaskInfo> dataList = new ArrayList<>();
        String type;
        switch (taskType) {
            case 0:
                type = "检测任务";
                break;
            case 1:
                type = "复检任务";
                break;
            case 2:
                type = "跟踪任务";
                break;
            default:
                type = "检测任务";
        }
        File sd = Environment.getExternalStorageDirectory();
        File f = new File(sd.getPath().concat("/").concat("检测系统").concat("/").concat(type).concat("/")); // 获取文件句柄
        File[] files = f.listFiles();
        Observable.fromArray(files).filter(new Predicate<File>() {
            @Override
            public boolean test(File file) throws Exception {
                String fileName = file.getName();
                return fileName.endsWith(".xlsx");
            }
        }).map(new Function<File, TaskInfo>() {
            @Override
            public TaskInfo apply(File file) throws Exception {
                TaskInfo taskInfo = EntityManager.getInstance().queryTaskInfoCount(file.getName(), taskType, true);
                if (taskInfo == null) {
                    taskInfo = new TaskInfo();
                    taskInfo.setTask_name(file.getName());
                    taskInfo.setTaskFilePath(file.getPath());
                    taskInfo.setLocalFile(true);
                    taskInfo.setTaskType(taskType);
                }
                return taskInfo;
            }
        }).subscribe(new Consumer<TaskInfo>() {
            @Override
            public void accept(TaskInfo taskInfo) throws Exception {
                dataList.add(taskInfo);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                throwable.printStackTrace();
            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                getV().onSuccess(dataList);
            }
        });
    }


    public void save2(List<TaskInfo> dataList) {
        NLog.d("LocalTask", "" + Thread.currentThread().toString());

        getV().showLoadDialog();
        Observable[] array = new Observable[dataList.size()];
        for (int i = 0; i < dataList.size(); i++) {
            TaskInfo info = dataList.get(i);
            Observable<TaskInfo> observable = Observable.just(info).subscribeOn(Schedulers.io()).flatMap(new Function<TaskInfo, ObservableSource<TaskInfo>>() {
                @Override
                public ObservableSource<TaskInfo> apply(TaskInfo taskInfo) throws Exception {
                    NLog.d("LocalTask", taskInfo.getTask_name() + Thread.currentThread());
                    NLog.d("LocalTask", "start+" + Kits.Date.getYmdhmsS(Calendar.getInstance().getTimeInMillis()));
                    taskInfo.setHadDowned(false);
                    EntityManager.getInstance().saveTaskInfo(taskInfo);
                    EntityManager.getInstance().delTaskItemInfoByParentId(taskInfo.get_ID());
                    return getTaskItems(taskInfo);
                }
            });
            array[i] = observable;
        }
        Observable.mergeArray(array).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<TaskInfo>() {
            @Override
            public void accept(TaskInfo result) throws Exception {
                NLog.d("LocalTask", "end+" + Kits.Date.getYmdhmsS(Calendar.getInstance().getTimeInMillis()));
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                NLog.d("LocalTask", "error");
                getV().showToast("导出失败");
                throwable.printStackTrace();
            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                NLog.d("LocalTask", "complete");
                getV().importSuccess();
            }
        });

    }

//    public void save(List<TaskInfo> dataList) {
//        getV().showLoadDialog();
//        Observable.fromIterable(dataList).flatMap(new Function<TaskInfo, ObservableSource<TaskInfo>>() {
//            @Override
//            public ObservableSource<TaskInfo> apply(TaskInfo taskInfo) throws Exception {
//                Log.d("LocalTask", taskInfo.toString());
//                EntityManager.getInstance().saveTaskInfo(taskInfo);
//                EntityManager.getInstance().delTaskItemInfoByParentId(taskInfo.get_ID());
//                return getTaskItems(taskInfo);
//            }
//        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<TaskInfo>() {
//            @Override
//            public void accept(TaskInfo result) throws Exception {
//
//            }
//        }, new Consumer<Throwable>() {
//            @Override
//            public void accept(Throwable throwable) throws Exception {
//                throwable.printStackTrace();
//            }
//        }, new Action() {
//            @Override
//            public void run() throws Exception {
//                getV().importSuccess();
//            }
//        });
//    }


    public Observable<TaskInfo> getTaskItems(final TaskInfo info) {
        return Observable.just(info).map(new Function<TaskInfo, TaskInfo>() {
            @Override
            public TaskInfo apply(TaskInfo taskInfo) throws Exception {
                List dataList = new ArrayList();
                try{
                    InputStream inputStream = new FileInputStream(taskInfo.getTaskFilePath());
                    XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
                    XSSFSheet sheet = workbook.getSheetAt(0);
                    int rowsCount = sheet.getPhysicalNumberOfRows();
                    for (int i = 0; i < rowsCount; i++) {
                        TaskItemInfo itemInfo = getTaskItemInfo(sheet, sheet.getRow(i), info.getTaskType());
                        itemInfo.setParentId(taskInfo.get_ID());
                        itemInfo.setFilePath(info.getTaskFilePath());
                        dataList.add(itemInfo);
                    }

                }catch (Exception ex){
                    ex.printStackTrace();
                }

                if (!Kits.Empty.check(dataList)) {
                    dataList.remove(0);
                    EntityManager.getInstance().saveTaskItemInfo(dataList);
                    taskInfo.setHadDowned(true);

                }else{
                    taskInfo.setIsErrorFile(true);
                }
                EntityManager.getInstance().saveTaskInfo(taskInfo);
                Log.d("LocalTask", "2" + taskInfo.getTask_name() + Thread.currentThread());
                Log.d("LocalTask", taskInfo.getTask_name() + "= " + dataList.size());
                return taskInfo;
            }
        });
    }


    private TaskItemInfo getTaskItemInfo(XSSFSheet sheet, Row row, int taskType) {

        int rowNum = row.getRowNum();
        int firstCellNum = row.getFirstCellNum();
        int lastCellNum = row.getLastCellNum();

        NLog.d("getTaskItemInfo", "rowNum=" + rowNum + " firstCellNum=" + firstCellNum + " lastCellNum=" + lastCellNum);
        TaskItemInfo info = new TaskItemInfo();
        info.setRowIndex(rowNum);
        for (int i = firstCellNum; i < lastCellNum; i++) {
            try{
                Cell cell = row.getCell(i);
                info.setCellIndex(firstCellNum);
                String cellTitle = sheet.getRow(0).getCell(i).getStringCellValue();
                String value = convertCellValueToString(cell);

                String cellType;
                if (null == cell) {
                    cellType = null;
                } else {
                    cellType = "" + cell.getCellType();
                }
                NLog.d("getTaskItemInfo", "i=" + i + " cellTitle=" + cellTitle + " value=" + value + " cellType=" + cellType);
                setItemValue(info, cellTitle, value);

            }catch (Exception ex){

            }

        }
        switch (taskType) {
            case 0:
            case 2:
                String testPerson = info.getTestPerson();
                String testValue = info.getTestValue();
                if (!TextUtils.isEmpty(testPerson)
                        && !TextUtils.equals(testPerson, "null")
                        && !TextUtils.equals(testValue, "null")
                        && !TextUtils.isEmpty(testValue)) {
                    info.setIsHadTest(true);
                }
                break;
            case 1:
                String repeatPerson = info.getRepeatPerson();
                String repeatValue = info.getRepeatValue();
                if (!TextUtils.isEmpty(repeatPerson)
                        && !TextUtils.equals(repeatPerson, "null")
                        && !TextUtils.equals(repeatValue, "null")
                        && !TextUtils.isEmpty(repeatValue)) {
                    info.setIsHadTest(true);
                }
                break;
        }
        return info;
    }

    private TaskItemInfo setItemValue(TaskItemInfo info, String cellTitle, String value) {
        switch (cellTitle) {
            case "装置":
                info.setDevice(value);
                break;
            case "区域":
                info.setArea(value);
                break;
            case "设备":
                info.setEquipment(value);
                break;
            case "标签号":
                info.setLabel(value);
                break;
            case "位置描述":
                info.setLocationDesc(value);
                break;
            case "组件类型":
                info.setAssemblyType(value);
                break;
            case "组件子类型":
                info.setAssemblyChildType(value);
                break;
            case "泄漏阈值":
                info.setLeakValue(value);
                break;
            case "检测最小停留时间(秒)":
                info.setMinStopTime(value);
                break;
            case "检测日期":
                info.setTestDate(value);
                break;
            case "检测仪器":
                info.setTestDevice(value);
                break;
            case "检测值":
                info.setTestValue(value);
                break;
            case "是否泄漏":
                info.setIsLeak(value);
                break;
            case "泄漏部位":
                info.setLeakLocation(value);
                break;
            case "背景值":
                info.setBackGround(value);
                break;
            case "室内":
                info.setIndoor(value);
                break;
            case "检测路径":
                info.setTestPath(value);
                break;
            case "每分滴漏数":
                info.setLeakSpeed(value);
                break;
            case "检测人员":
                info.setTestPerson(value);
                break;
            case "组件图片":
                info.setTestPic(value);
                break;
            case "备注":
                info.setDesc(value);
                break;
            case "复测日期":
                info.setRepeatDate(value);
                break;
            case "复测仪器":
                info.setRepeatDevice(value);
                break;
            case "复测值":
                info.setRepeatValue(value);
                break;
            case "复测人员":
                info.setRepeatPerson(value);
                break;
            default:
        }
        return info;
    }

    private String convertCellValueToString(Cell cell) {
        if (cell == null) {
            return "";
        }
        String returnValue = "";
        switch (cell.getCellType()) {
            case 0: // 数字
                Double doubleValue = cell.getNumericCellValue();
                String valueStr = String.valueOf(doubleValue);
                NLog.d("valueStr", "doubleValue=" + doubleValue);
                DecimalFormat df;
                if (valueStr.contains(".0")) {
                    df = new DecimalFormat("0");
                } else {
                    df = new DecimalFormat("0.0");
                }
                NLog.d("valueStr", "valueStr=" + valueStr);
                returnValue = df.format(doubleValue);
                break;
            case 1: // 字符串
                returnValue = cell.getStringCellValue();
                break;
            case 4: // 布尔
                Boolean booleanValue = cell.getBooleanCellValue();
                returnValue = booleanValue.toString();
                break;
            case 3: // 空值
                break;
            case 2: // 公式
                returnValue = cell.getCellFormula();
                break;
            case 5: // 故障
                cell.getDateCellValue();
                break;
            default:
                break;
        }
        return returnValue;
    }


}
